package com.hzit.zuul.fitler;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class PreFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        String token = request.getParameter("token");
        if (StringUtils.isEmpty(token)) {

            HttpServletResponse response = requestContext.getResponse();
            response.setCharacterEncoding("utf-8");  //设置字符集
            response.setContentType("application/json; charset=utf-8"); //设置相应格式

            requestContext.setSendZuulResponse(false);//访问不通过
            requestContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
            requestContext.setResponseBody("{\"status\":\"401\", \"text\":\"request error!,必须指定token\"}");
        }

        // 校验通过，把登陆信息放入上下文信息，继续向后执行
        requestContext.set("token", token);
        return null;
    }
}
